<template>
  <a-input-search
    v-model:value="searchParams.text"
    placeholder="请输入你想搜索的内容"
    enter-button="搜一下"
    size="large"
    @search="onSearch"
  />
  <MySpilt />
  <a-tabs v-model:activeKey="activeKey" @change="onTabChange">
    <a-tab-pane key="post" tab="文章">
      <PostPage :post-list="postList" />
    </a-tab-pane>
    <a-tab-pane key="picture" tab="图片">
      <PicturePage :picture-list="pictureList" />
    </a-tab-pane>
    <a-tab-pane key="person" tab="用户">
      <PersonPage :user-list="userList" />
    </a-tab-pane>
  </a-tabs>
</template>

<script setup lang="ts">
import { ref, watchEffect } from "vue";
import PostPage from "@/components/PostPage.vue";
import PicturePage from "@/components/PicturePage.vue";
import PersonPage from "@/components/PersonPage.vue";
import MySpilt from "@/components/MySpilt.vue";
import { useRoute, useRouter } from "vue-router";
import myAxios from "@/plugins/myAxios";

const route = useRoute();
const router = useRouter();
const activeKey = ref();
const userList = ref([]);
const postList = ref([]);
const pictureList = ref([]);
const initSearchParams = {
  text: "",
  pageSize: 20,
  pageNum: 1,
};

const searchParams = ref({
  text: "",
});
//监听页面参数变化
watchEffect(() => {
  //将params中category赋值给activeKey，让页面联动
  activeKey.value = route.params.category;
  searchParams.value = {
    ...initSearchParams,
    text: route.query.text,
  } as any;
});

const loadData = (params: any) => {
  const query = {
    ...params,
    searchText: params.text,
  };
  myAxios.post("/search/all", query).then((res: any) => {
    console.log(res);
    userList.value = res.userList;
    postList.value = res.postList;
    pictureList.value = res.pictureList;
  });
};
//初始化数据
loadData(initSearchParams);
//搜索业务
const onSearch = (value: string) => {
  console.log(value);
  router.push({
    query: searchParams.value,
  });
  //搜索过后加载数据
  loadData(searchParams.value);
};
//tab切换业务
const onTabChange = (key: string) => {
  router.push({
    path: `/${key}`,
    query: searchParams.value,
  });
  loadData(searchParams.value);
};
</script>
